package com.wejoy.video.middle.station.data.service.wechat.impl;

import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.data.constant.RedisKeys;
import com.wejoy.video.middle.station.data.domain.system.SysBaseParam;
import com.wejoy.video.middle.station.data.service.system.ISysBaseParamService;
import com.wejoy.video.middle.station.data.service.wechat.IWeChatService;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.util.weChat.WeChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class WcChatServiceImpl implements IWeChatService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISysBaseParamService sysBaseParamService;

    private String getToken() {
        String token = (String) redisTemplate.opsForValue().get(RedisKeys.WECHAT_API_TOKEN);
        if(StringUtils.isEmpty(token)){
            JSONObject jsonObject = WeChatUtils.getToken();
            token=jsonObject.getString("access_token");
            Integer expiresIn = jsonObject.getInteger("expires_in");
            redisTemplate.opsForValue().set(RedisKeys.WECHAT_API_TOKEN,token,expiresIn-100,TimeUnit.SECONDS);
        }
        return token;
    }

    @Override
    public JSONObject getDepartment() {
        return  WeChatUtils.getDepartment(getToken());
    }

    @Override
    public JSONObject getUserListByDepartment(Integer departmentId, Integer fetchChild) {
        return WeChatUtils.getUserListByDepartment(getToken(),departmentId,fetchChild);
    }

    @Override
    public void sendMessage(List<String> userIdList,String departmentName) {
        String userIds = StringUtils.join(userIdList,"|");
        SysBaseParam wechatMessageContent = sysBaseParamService.getOneByUniCode("WECHAT_MESSAGE_CONTENT");
        if(!ObjectUtils.isEmpty(wechatMessageContent)){
            WeChatUtils.sendMessage(getToken(),userIds,String.format(wechatMessageContent.getValue(),departmentName));
        }
    }
}
